package com.chendx.store.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chendx.model.common.dtos.PageResponseResult;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.goods.dto.BrandDto;
import com.chendx.model.goods.pojo.Brand;
import com.chendx.model.goods.pojo.CategoryBrand;
import com.chendx.store.goods.mapper.BrandMapper;
import com.chendx.store.goods.mapper.CategoryBrandMapper;
import com.chendx.store.goods.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by chendx on 2022/4/19.
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper,Brand> implements BrandService {

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Override
    public ResponseResult loadBrand(BrandDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        LambdaQueryWrapper<Brand> queryWrapper = new LambdaQueryWrapper();
        if (!StringUtils.isEmpty(dto.getName())){
            queryWrapper.like(Brand::getName,dto.getName());
        }
        if (!StringUtils.isEmpty(dto.getStatus())){
            queryWrapper.eq(Brand::getStatus,dto.getName());
        }
        if (!StringUtils.isEmpty(dto.getLetter())){
            queryWrapper.like(Brand::getStatus,dto.getName());
        }
        dto.setSize(30);
        Page ipage = new Page(dto.getPage(),dto.getSize());
        IPage<Brand> result = page(ipage, queryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(), (int) result.getTotal());
        responseResult.setData(result.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult loadByCategory(Integer categoryId) {
        if (StringUtils.isEmpty(categoryId)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<CategoryBrand> categoryBrands = categoryBrandMapper.selectList(Wrappers.<CategoryBrand>lambdaQuery().eq(CategoryBrand::getCategoryId, categoryId));
        List<Integer> brandIds = categoryBrands.stream().map(x -> x.getBrandId()).collect(Collectors.toList());
        List<Brand> brandList = list(Wrappers.<Brand>lambdaQuery().in( Brand::getId, brandIds));

        return ResponseResult.okResult(brandList);
    }
}
